import React, { useState, useEffect } from "react";
import axios from "axios";
import { Layout, Menu } from "antd";
import { useNavigate, useLocation } from "react-router-dom";
import {
  UserOutlined,
  SettingOutlined,
  UploadOutlined,
  AuditOutlined,
  FormOutlined,
  HomeOutlined,
} from "@ant-design/icons";
import { useSelector } from "react-redux";
const { Sider } = Layout;

export default function SideMenu() {
  const [items, setItems] = useState([]);
  const navigater = useNavigate();
  const location = useLocation();
  const iconMap = {
    首页: <HomeOutlined />,
    用户管理: <UserOutlined />,
    用户列表: <UserOutlined />,
    权限管理: <SettingOutlined />,
    新闻管理: <FormOutlined />,
    审核管理: <AuditOutlined />,
    发布管理: <UploadOutlined />,
  };
  // 根据当前路径设置选中的菜单项
  const [selectedKeys, setSelectedKeys] = useState([location.pathname]);
  //处理items的首页展示数据添加icon属性
  useEffect(() => {
    //获取当前登录用户的权限数据
    const {
      role: { rights },
    } = JSON.parse(localStorage.getItem("token"));

    setSelectedKeys([location.pathname]);
    const getItems = async () => {
      const res = await axios.get(
        "http://localhost:3000/rights?_embed=children"
      );
      //处理首页部分标签不需要展示问题
      //处理完的新结果
      let newRes = [];
      res.data.forEach((item) => {
        // 分开处理 处理存在children的和不存在的
        if (item.children.length === 0 && rights.includes(item.key)) {
          delete item.children;
          newRes.push(item);
        } else {
          let newResChildren = [];
          item.children.forEach((element) => {
            //如果是首页就添加到新的children数组中去 并且还要判断当前登录用户是不是包含该权限
            if (element.pagepermisson === 1 && rights.includes(element.key)) {
              newResChildren.push(element);
            }
          });
          //只有当用户有父级权限或者有子级权限时，才添加该菜单项
          // 如果用户没有某个模块的权限，且该模块下没有任何可访问的子菜单，该模块就不会显示在侧边菜单中
          // 如果用户有父级权限，无论子菜单如何，都会显示该模块
          if (rights.includes(item.key) || newResChildren.length > 0) {
            newRes.push({ ...item, children: newResChildren });
          }
        }
      });
      setItems(newRes);

      const setIcon = (item, iconMap) => {
        // 创建副本以避免直接修改原数组
        const newItems = JSON.parse(JSON.stringify(item));
        newItems.forEach((element) => {
          for (let key in iconMap) {
            if (key === element.label) {
              element.icon = iconMap[key];
            }
          }
        });
        return newItems;
      };
      setItems(setIcon(newRes, iconMap));
    };
    getItems();
  }, [location.pathname]);

  const openKey = "/" + location.pathname.split("/")[1];

  // 添加这个过滤函数 防止antd组件报错 我们传递出的组件如果有多余属性就会报错
  const filterMenuItems = (items) => {
    return items.map((item) => {
      // 创建一个新的对象，只包含Menu组件需要的属性
      const filteredItem = {
        key: item.key,
        label: item.label,
        icon: item.icon,
        children: item.children ? filterMenuItems(item.children) : undefined,
      };

      return filteredItem;
    });
  };

  const {collapsed}=useSelector(state=>state.collapsed)
  return (
    <Sider trigger={null} collapsible collapsed={collapsed}>
      <div
        className="demo-logo-vertical"
        style={{
          lineHeight: "32px",
          backgroundColor: "rgba(255,255,255,0.2)",
          textAlign: "center",
          margin: "5px",
          borderRadius: "10px",
          color: "white",
          fontSize: "18px",
        }}
      >
        全球新闻发布系统
      </div>
      <Menu
        theme="dark"
        mode="inline"
        selectedKeys={selectedKeys}
        defaultOpenKeys={[openKey]}
        items={filterMenuItems(items)} // 使用过滤后的数据
        onClick={(item) => {
          navigater(item.key);
          window.scrollTo(0, 0);
        }}
      />
    </Sider>
  );
}
